package demo1;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool=new MyThreadPool(10,30);
        for (int i = 0; i < 1000; i++) {
            int id=i;
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    System.out.println(id+" "+Thread.currentThread().getName());
                }
            };
            myThreadPool.submit(runnable);
        }
    }
}
//模拟线程池
//1、核心线程数、最大线程数--管理策略
//2、非核心线程最大存活时间、
//3、任务队列BlockingQueue
//4、submit提交任务方法
class MyThreadPool{
   private BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(1000);
    private int maxThreadNum;
    private int currentThread;

    public MyThreadPool(int coreNum,int maxThreadNum) {
        this.maxThreadNum=maxThreadNum;
        this.currentThread=coreNum;
        for (int i = 0; i < coreNum; i++) {
            Thread t=new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        try {
                            Runnable task=queue.take();
                            task.run();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
            t.start();
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
        if(queue.size()>500&&currentThread<=maxThreadNum){
            creatThread();
            currentThread++;
        }
    }
    public void creatThread(){
        Thread t=new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Runnable task=queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        t.start();
    }
}